package com.fubowen.reader.extension

import android.graphics.Bitmap
import android.graphics.Canvas
import android.graphics.Color
import android.graphics.Matrix
import android.graphics.Paint
import android.graphics.PorterDuff
import android.graphics.PorterDuffXfermode
import java.io.BufferedOutputStream
import java.io.ByteArrayOutputStream
import java.io.File
import java.io.FileOutputStream
import java.io.InputStream

fun createEmptyImage(): InputStream {
    val bitmap = Bitmap.createBitmap(1, 1, Bitmap.Config.ARGB_8888)
    bitmap.eraseColor(Color.TRANSPARENT)
    val outputStream = ByteArrayOutputStream()
    bitmap.compress(Bitmap.CompressFormat.PNG, 100, outputStream)
    val byteArray = outputStream.toByteArray()
    return byteArray.inputStream()
}

fun Bitmap.saveBitmapToFile(filePath: String): String? {
    val path = filePath.substringBeforeLast("/")
    return File(path).let {
        if (!it.exists()) it.mkdirs()
        val file = File(filePath)
        try {
            FileOutputStream(file).use { fs ->
                BufferedOutputStream(fs).use { bs ->
                    this.compress(Bitmap.CompressFormat.JPEG, 100, bs)
                }
            }
            file.absolutePath
        } catch (e: Exception) {
            null
        }
    }
}

fun Bitmap.toByteArray(): ByteArray {
    ByteArrayOutputStream().use {
        this.setSize(144, 144).compress(Bitmap.CompressFormat.JPEG, 100, it)
        return it.toByteArray()
    }
}

fun Bitmap.setSize(width: Int, height: Int): Bitmap {
    val w = this.width
    val h = this.height
    val sw = width.toFloat() / w
    val sh = height.toFloat() / h
    val matrix = Matrix()
    matrix.postScale(sw, sh)
    return Bitmap.createBitmap(this, 0, 0, w, h, matrix, true)
}

fun Bitmap.setCircle(): Bitmap {
    val width = this.width
    val paint = Paint()
    paint.isAntiAlias = true
    val bitmap = Bitmap.createBitmap(width, width, Bitmap.Config.ARGB_8888)
    val canvas = Canvas(bitmap)
    val r = width.toFloat() / 2
    canvas.drawCircle(r, r, r, paint)
    paint.xfermode = PorterDuffXfermode(PorterDuff.Mode.SRC_IN)
    canvas.drawBitmap(this, 0f, 0f, paint)
    return bitmap
}